package com.fer.hr.nmbp.lab2.gui;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import org.apache.ibatis.session.SqlSession;

import com.hr.fer.nmbp.lab2.domain.Room;
import com.hr.fer.nmbp.lab2.persistence.RoomMapper;

public class AddRoomWindow extends JFrame {
	private static final long serialVersionUID = 2970733206136902605L;
	
	private JPanel contentPane;
	private JTextField tbRoomNum;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AddRoomWindow frame = new AddRoomWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void closeClick(){
		this.dispose();
	}
	/**
	 * Create the frame.
	 */
	public AddRoomWindow() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 269, 192);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblRoomNumber = new JLabel("Broj sobe:");
		lblRoomNumber.setBounds(10, 27, 90, 14);
		contentPane.add(lblRoomNumber);
		
		tbRoomNum = new JTextField();
		tbRoomNum.setBounds(113, 24, 86, 20);
		contentPane.add(tbRoomNum);
		tbRoomNum.setColumns(10);
		
		JLabel lblNewLabel = new JLabel("Broj kreveta:");
		lblNewLabel.setBounds(10, 52, 76, 14);
		contentPane.add(lblNewLabel);
		
		final JComboBox cbBedNum = new JComboBox();
		cbBedNum.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5"}));
		cbBedNum.setBounds(113, 49, 86, 20);
		contentPane.add(cbBedNum);
		
		JButton btnOdustani = new JButton("Odustani");
		btnOdustani.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				closeClick();
			}
		});
		btnOdustani.setBounds(11, 94, 89, 23);
		contentPane.add(btnOdustani);
		
		JButton btnSpremi = new JButton("Spremi");
		btnSpremi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				SqlSession session = null;
				session = MainWindow.sessionFactory.openSession();
				
				Room room = new Room(
						Integer.parseInt(tbRoomNum.getText()),
						Integer.parseInt((String)cbBedNum.getSelectedItem())
				);
				RoomMapper mapper = session.getMapper(RoomMapper.class);
				mapper.insert(room);
				
				session.commit();
				
				session.close();
				
				closeClick();
			}
		});
		btnSpremi.setBounds(110, 94, 89, 23);
		contentPane.add(btnSpremi);
	}
}
